
from concurrent_log_handler import ConcurrentRotatingFileHandler
import logging
import asyncio
import functools
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Optional
from .config import Config

# 创建基础logger
_base_logger = logging.getLogger(__name__)
_base_logger.setLevel(logging.DEBUG)
_base_logger.handlers = []  # 清空默认处理器

# 使用ConcurrentRotatingFileHandler
handler = ConcurrentRotatingFileHandler(
    Config.LOG_FILE,
    maxBytes=Config.MAX_BYTES,
    backupCount=Config.BACKUP_COUNT,
    encoding="utf-8"
)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
))
_base_logger.addHandler(handler)

# 创建线程池用于异步日志操作
_log_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="AsyncLogger")

class AsyncLogger:
    """异步日志包装器
    
    所有日志操作都会在后台线程中异步执行，不会阻塞主线程。
    """
    
    def __init__(self, base_logger: logging.Logger):
        self._logger = base_logger
        self._loop = None
    
    def _get_loop(self) -> asyncio.AbstractEventLoop:
        """获取当前事件循环"""
        try:
            return asyncio.get_running_loop()
        except RuntimeError:
            # 如果没有运行中的事件循环，创建一个新的
            return asyncio.new_event_loop()
    
    async def _async_log(self, level: int, msg: Any, *args, **kwargs) -> None:
        """异步执行日志记录"""
        loop = self._get_loop()
        
        # 在线程池中执行日志操作
        await loop.run_in_executor(
            _log_executor,
            functools.partial(self._logger.log, level, msg, *args, **kwargs)
        )
    
    def _sync_log(self, level: int, msg: Any, *args, **kwargs) -> None:
        """同步日志记录（用于非异步环境）"""
        try:
            # 尝试在当前事件循环中创建任务
            loop = self._get_loop()
            if loop.is_running():
                # 如果事件循环正在运行，创建任务
                asyncio.create_task(self._async_log(level, msg, *args, **kwargs))
            else:
                # 如果没有运行中的事件循环，直接同步记录
                self._logger.log(level, msg, *args, **kwargs)
        except Exception:
            # 如果异步操作失败，回退到同步记录
            self._logger.log(level, msg, *args, **kwargs)
    
    # 异步日志方法
    async def adebug(self, msg: Any, *args, **kwargs) -> None:
        """异步DEBUG级别日志"""
        await self._async_log(logging.DEBUG, msg, *args, **kwargs)
    
    async def ainfo(self, msg: Any, *args, **kwargs) -> None:
        """异步INFO级别日志"""
        await self._async_log(logging.INFO, msg, *args, **kwargs)
    
    async def awarning(self, msg: Any, *args, **kwargs) -> None:
        """异步WARNING级别日志"""
        await self._async_log(logging.WARNING, msg, *args, **kwargs)
    
    async def aerror(self, msg: Any, *args, **kwargs) -> None:
        """异步ERROR级别日志"""
        await self._async_log(logging.ERROR, msg, *args, **kwargs)
    
    async def acritical(self, msg: Any, *args, **kwargs) -> None:
        """异步CRITICAL级别日志"""
        await self._async_log(logging.CRITICAL, msg, *args, **kwargs)
    
    # 同步日志方法（兼容性）
    def debug(self, msg: Any, *args, **kwargs) -> None:
        """DEBUG级别日志（自动异步化）"""
        self._sync_log(logging.DEBUG, msg, *args, **kwargs)
    
    def info(self, msg: Any, *args, **kwargs) -> None:
        """INFO级别日志（自动异步化）"""
        self._sync_log(logging.INFO, msg, *args, **kwargs)
    
    def warning(self, msg: Any, *args, **kwargs) -> None:
        """WARNING级别日志（自动异步化）"""
        self._sync_log(logging.WARNING, msg, *args, **kwargs)
    
    def error(self, msg: Any, *args, **kwargs) -> None:
        """ERROR级别日志（自动异步化）"""
        self._sync_log(logging.ERROR, msg, *args, **kwargs)
    
    def critical(self, msg: Any, *args, **kwargs) -> None:
        """CRITICAL级别日志（自动异步化）"""
        self._sync_log(logging.CRITICAL, msg, *args, **kwargs)
    
    # 属性代理
    @property
    def level(self) -> int:
        return self._logger.level
    
    @level.setter
    def level(self, value: int) -> None:
        self._logger.setLevel(value)
    
    def setLevel(self, level: int) -> None:
        """设置日志级别"""
        self._logger.setLevel(level)
    
    def isEnabledFor(self, level: int) -> bool:
        """检查是否启用指定级别的日志"""
        return self._logger.isEnabledFor(level)
    
    async def shutdown(self) -> None:
        """关闭异步logger，等待所有日志任务完成"""
        _log_executor.shutdown(wait=True)

# 创建全局异步logger实例
logger = AsyncLogger(_base_logger)

# 为了向后兼容，也导出原始logger
base_logger = _base_logger

